﻿using Assets.Scripts.DL.Enemy.CommonEnemy;
using Assets.Scripts.DL.Enemy.SpriderBoss;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Assets.Scripts.DL.Enemy.YaSuo {
	public class YasuoMove : CommonState<YasuoController> {
		bool _moveOver;
		readonly Timer _timer = new();
		float _moveTime;

		public YasuoMove(YasuoController controller, StateEnum stateName) : base(controller, stateName) {
			AddConditionToSelf(() => true);


			AddNewTransition(StateEnum.Idle, () => _moveOver);
		}

		public override void Enter() {
			if (_controller.Player != null) {
				var px = _controller.GetPlayerPos().x;
				var x = _controller.transform.position.x;
				var dir = px > x ? 1 : -1;
				_controller.ChangeFaceDir(dir);
			}
			else {
				var t = UnityEngine.Random.Range(0, 2);
				if (t == 1)
					_controller.ChangeFaceDir();
				var range = _controller.Config.MoveTimeRange;
				_moveTime = UnityEngine.Random.Range(range.x, range.y);
			}
			var v = _controller.Config.MoveSpeed;
			_controller.Velocity = new Vector2(_controller.FaceDir * v, 0);
			_controller.PlayAnim(StateName);
			_moveOver = false;
			_timer.Reset();
		}

		public override void Exit() {
			_controller.Velocity = Vector2.zero;
		}

		public override void Update() {
			if (_controller.IsTouchingWall() || !_controller.IsOnGround()) {
				_moveOver = true;
			}
			//找到了player
			if (_controller.Player != null) {
				if (IsShouldChangeDir()) {
					if (!IsNearPlayer()) {
						_controller.ChangeFaceDir();
					}
					else {
						_moveOver = true;
					}
				}
			}
			else {
				if (_timer.Elapsed > _moveTime) {
					_moveOver = true;
				}
			}
		}
		bool IsShouldChangeDir() {
			var dir = _controller.transform.localScale.x;
			var targeDir = _controller.transform.position.x < _controller.Player.transform.position.x ?
				1 : -1;
			return dir != targeDir;
		}

		bool IsNearPlayer() {
			var player = _controller.Player.transform.position.x;
			var p = _controller.transform.position.x;

			return Mathf.Abs(p - player) < 2;
		}
	}
}
